//
//  CardEditViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-5.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CardEditViewController.h"
#import "TextFieldCell.h"
#import "DBConnection.h"
#import "GuaziAppDelegate.h"
#import "StringUtil.h"
#import "OperationLog.h"
#import "DataUploadService.h"


@interface CardEditViewController(private)
- (BOOL) validate;
@end



@implementation CardEditViewController

@synthesize  cellDelegate;
@synthesize card;
@synthesize isNew;


- (id)initWithCard:(Card*) aCard style:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.card = [Card cardWithCard:aCard];
        isNew = NO;
        
        self.cellDelegate = [[[CardEditCellDelegate alloc] init] autorelease];
        self.cellDelegate.card = self.card;
        self.cellDelegate.isNew = NO;
    }
    return self;
}


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.card = [[[Card alloc] init] autorelease];
        isNew = YES;
        
        self.cellDelegate = [[[CardEditCellDelegate alloc] init] autorelease];
        self.cellDelegate.card = self.card;
        self.cellDelegate.isNew = YES;
    }
    return self;
}


- (void)dealloc
{
    [cellDelegate release];
    [card release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle


- (void) save
{
    BOOL isvalid = [self validate];
	if ( !isvalid ) return;
	
	if ( self.cellDelegate.currentTextField ) {
		[self.cellDelegate setValueByTextField:self.cellDelegate.currentTextField];
	}
	
    long long ownerId = [GuaziAppDelegate getAppDelegate].user.userId;

    if ( isNew ) {
        long long cardId = [DBConnection createRandomNum:12];
        card.cardId = cardId;
        card.userId = [GuaziAppDelegate getAppDelegate].user.userId;
        [card updateDB];
        
        OperationLog* log = [[OperationLog alloc] initWithModule:kOperationLogModuleCard 
                                                       operation:kOperationLogOperationAdd 
                                                           refId:[NSString stringWithFormat:@"%lld", ownerId]
                                                          params:[card toString]];
        [log insert];
        [log release];
		
		//refresh
		MyCardsViewController* controller = [[GuaziAppDelegate getAppDelegate] myCardsViewController];
		if ( controller ) {
			[controller refreshAddCard:card];
		}
		
    }
    else {
		[card updateDB];

        OperationLog* log = [[OperationLog alloc] initWithModule:kOperationLogModuleCard 
                                                       operation:kOperationLogOperationAdd 
                                                           refId:[NSString stringWithFormat:@"%lld", ownerId]
                                                          params:[card toString]];
        [log insert];
        [log release];
    }
    
    [[DataUploadService sharedInstance] run];

	[self.navigationController popViewControllerAnimated:YES];
}


- (BOOL) validate 
{
	card.name = [card.name trim];
	card.company = [card.company trim];
	card.position = [card.position trim];
	card.address = [card.address trim];
	card.mobile = [card.mobile trim];
	card.tel = [card.tel trim];
	card.fax = [card.fax trim];
	card.postcode = [card.postcode trim];
	card.email = [card.email trim];
	
	NSString* message = nil;
	if ( [card.name length] == 0 ) {
		message = @"请输入姓名！";
	}
	else if ([card.company length] == 0 ) {
		message = @"请输入公司名称！";
	}
	else if ( [card.position length] == 0 ) {
		message = @"请输入职务!";
	}
	else if ( [card.mobile length] == 0 ) {
		message = @"请输入手机号";
	}
		
	if ( message ) {
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"错误" 
															message:message 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return NO;
	}
	return YES;
}


- (void) buildBarButtonItems
{
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)] autorelease];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self buildBarButtonItems];
    
    if ( isNew ) {
        self.navigationItem.title = @"新名片";
    }
    else {
        self.navigationItem.title = @"编辑名片";
    }
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    self.cellDelegate = nil;
    self.card = nil;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 2;
    }
    else if ( section == 1 ) {
        return 3;
    }
    else {
        return 4;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CardEditCell";
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    NSInteger tag = -1;
    if ( section == 0 ) {
        if ( row == 0 ) tag = kTagName;
        else if ( row == 1 ) tag = kTagMobile;
    }
    else if ( section == 1 ) {
        if ( row == 0 ) tag = kTagCompony;
        else if ( row == 1 ) tag = kTagPosition;
        else if ( row == 2 ) tag = kTagAddress;
    }
    else if ( section == 2 ) {
        if ( row == 0 ) tag = kTagTel;
        else if ( row == 1 ) tag = kTagFax;
        else if ( row == 2 ) tag = kTagEmail;
        else if ( row == 3 ) tag = kTagPostcode;
    }
    
    TextFieldCell *cell = (TextFieldCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	[cell updateWithDelegate:self.cellDelegate tag:tag];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}


- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}


@end
